const Fly = require("flyio/dist/npm/wx") 
import Env from './Env'
import $n from './nothing'
import store from '@/store'
import $context from './AppContext'
const request = new Fly
/**
 * 请求拦截
 */
request.interceptors.request.use((config, promise) => {
  // 超时设置
  config.timeout = 30000
  // 从环境变量中取 BASE_URL
  config.baseURL = Env.getBaseURL()
  // JSON格式化，未指定时，默认true
  config.parseJson = $n._isNotNull(config.parseJson) ? config.parseJson : true
  // 如指定_token == true，则在headers中跟上相关token信息
  if (config._token) config.headers['Authorization'] = store.getters.appUser.token
console.warn('####### token', store.getters.appUser.token)
  if (process.env.NODE_ENV === 'development') console.warn('####### API Request: ', config)
  return config
})

/**
 * 响应拦截
 */
request.interceptors.response.use(
  (response, promise) => {
    let data = response.data || {status: false, msg: '服务器未响应结果'};
	if (process.env.NODE_ENV === 'development') console.warn('####### API Response: ', data)
    if (data.code == 401 || data.code == 400) {
		$context.logout(this);
		uni.showToast({title: '请登录', icon: 'none'})
		uni.switchTab({url: '/pages/index/mine'});
    } else if(data.code == 403) return promise.resolve({status: false, msg: '请求服务未授权！'})
		else return promise.resolve(data)
  },
  (error, promise) => {
		if (process.env.NODE_ENV === 'development') console.error('####### API Response error: ', error)
		if (error.status === 0) return promise.reject('网络连接异常')
		else if (error.status === 1) return promise.reject('网络连接超时')
		if (error.code == 401 || error.code == 400) {
			$context.logout(this);
			uni.showToast({title: '请登录', icon: 'none'})
			uni.switchTab({url: '/pages/index/mine'});
		} else if(error.code == 403) {
			uni.showToast({title: '没权限', icon: 'none'})
			uni.switchTab({url: '/pages/index/mine'});
		} else return promise.reject(error.response && error.response.data ? error.response.data.msg  : '网络错误')
  }
)
export default request
